package loveqq.webflux.handler;

import loveqq.webflux.entity.User;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Controller
public class UserHandler {

    @Bean
    public RouterFunction<ServerResponse> userRouter() {
        /*
        RouterFunctions.route()的GET()或POST()方法，或者path()里面的，如：
            Builder GET(String pattern, HandlerFunction<ServerResponse> handlerFunction);
        handlerFunction如下：
            @FunctionalInterface
            public interface HandlerFunction<T extends ServerResponse> {
                Mono<T> handle(ServerRequest request);
            }
        根据这个方法格式编写handler方法，就是以前的controller方法
         */
        return RouterFunctions.route()
                .path("/user", builder -> builder
                        .GET("/getById/{id}", this::getById)
                        .GET("/all", this::all)
                        .POST("/allUser", this::all)
                ).build();
    }

    /**
     * 根据ID获取用户信息
     */
    public Mono<ServerResponse> getById(ServerRequest request) {
        // 根据request获取参数
        Long id = Long.valueOf(request.pathVariable("id"));
        Mono<User> userMono = Mono.just(
                // 假设从数据库查询出来
                new User().setId(id).setName("Hello").setAge(22)
        );
        // 返回response
        return ServerResponse.ok().body(userMono, User.class);
    }

    /**
     * 获取全部用户
     */
    public Mono<ServerResponse> all(ServerRequest request) {
        return ServerResponse.ok().body(Flux.just(
                // 假设从数据库查询出来
                new User().setId(1L).setName("name-1").setAge(21),
                new User().setId(2L).setName("name-2").setAge(22),
                new User().setId(3L).setName("name-3").setAge(23)
        ), User.class);
    }

}
